package mall.kotlin.com.myapplication.proxy;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import mall.kotlin.com.myapplication.R;

public class ProxyActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_proxy);
        //静态代理
        ShopPhone shopPhone = new ShopPhone();
        ProxyShopPhone proxyShopPhone = new ProxyShopPhone(shopPhone);
        proxyShopPhone.shopPhone("代购购买手机");
        //动态代理
        final ShopPhone shopPhone1 = new ShopPhone();
        shopPhone1.shopPhone("大陆自己买");
        IsShopPhone proxy = (IsShopPhone) Proxy.newProxyInstance(shopPhone1.getClass().getClassLoader(), shopPhone1.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object invoke = method.invoke(shopPhone1, args);
                return invoke;
            }
        });
        proxy.shopPhone("通过代购买的");

        //代理工厂
        IsShopPhone proxy2 = (IsShopPhone) new Proxyfactory(shopPhone1).getproxyInstance();
        proxy2.shopPhone("通过工厂代购买的");
    }

    //静态代理/////////////////////////////////////////////////////////////////
    //接口,代理类,和委托类都需要实现
    interface IsShopPhone {
        void shopPhone(String string);
    }

    //目标对象,实现接口,
    class ShopPhone implements IsShopPhone {

        @Override
        public void shopPhone(String string) {

        }
    }

    //代理对象也实现接口
    class ProxyShopPhone implements IsShopPhone {
        IsShopPhone mShopPhone;

        public ProxyShopPhone(IsShopPhone mShopPhone) {
            this.mShopPhone = mShopPhone;
        }

        @Override
        public void shopPhone(String string) {
            mShopPhone.shopPhone(string);
        }
    }
    ///////////////////////////////////////////////////////////////////
}
